﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.Enums;
using ThresholdAssistant.Http.Extensions;
using ThresholdAssistant.NLogSdk;
using ThresholdAssistant.Tools;
using System;
using System.Net;
using System.Threading.Tasks;

namespace ThresholdAssistant.Attributes
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
	public class GlobalExceptionAttribute : IAsyncExceptionFilter, IFilterMetadata
    {
        /// <summary>
        /// 发生异常时调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
		public async Task OnExceptionAsync(ExceptionContext context)
        {
            Exception ex = context.Exception;
            context.ExceptionHandled = true;
            var serialNo = context.HttpContext.Request.Headers.GetSerialNo();

            var result = new ContractResult();
            result.SetError(ErrorTypeEnum.Application_Error);
            context.Result = new JsonResult(result);
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            NLogUtil.Error(new NLogModel()
            {
                Type = "All",
                ReqId = serialNo,
                Url = context.HttpContext.Request.Path,
                Response = ex.JsonCompressAndEscape(),
                Content = $"【头部信息】{JsonConvert.SerializeObject(context.HttpContext.Request.Headers)}，【错误信息】{ex}"
            });
            await Task.CompletedTask;
        }
    }
}